#include <iostream>
#include <arpa/inet.h> //for inet_pton
#include <stdlib.h>
#include "SockClient.h"

using namespace std;


SockClient::SockClient()
{
	servaddrlen=sizeof(servaddr);
	bzero((struct sockaddr*)&servaddr,servaddrlen);
	
	cliaddrlen=sizeof(cliaddr);
	bzero((struct sockaddr*)&cliaddr,cliaddrlen);

	inBuf=(char *)malloc(1024);
	outBuf=(char *)malloc(1024);
}

SockClient::~SockClient()
{
	free(inBuf);
	free(outBuf);
}

bool SockClient::SetAddr(string ip,short port)
{
	int ret;
	
	servaddr.sin_family=AF_INET;
	servaddr.sin_port=htons(port);
	
	ret = inet_pton(AF_INET,ip.c_str(),&servaddr.sin_addr);
	if(ret < 0){
		Err();
        return false;
    } 
    
    return true;		
}

bool SockClient::Socket()
{
	sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(sockfd < 0){
		Err();
		return false;
	}
	
	return true;	
}

bool SockClient::Connect()
{
	int ret;
	
	ret=connect(sockfd,(struct sockaddr*)&servaddr,servaddrlen);
	if(ret == -1){
		Err();
		return false;	
	}
	
	return true;
}

bool SockClient::Send()
{
	int ret;
	
	ret = sendto(sockfd,outBuf,1024,0,(struct sockaddr*)&servaddr,
					servaddrlen);
	if(ret < 0){
		Err();
		return false;	
	}
	
	return true;
}

bool SockClient::Receive()
{
	int ret;
	
	bzero(inBuf,1024);
	ret = recvfrom(sockfd,inBuf,1024,0,(struct sockaddr*)&servaddr,&servaddrlen);
	if(ret < 0){
		Err();
		return false;	
	}

	return true;
}

bool SockClient::StartClient(string ip,short port)
{
	int ret;

	cout<<"Starting client..."<<endl;
	
	if(!Socket()){
		return false;	
	}
	
	SetAddr(ip,port);
	
	if(!Connect()){
		return false;	
	}
	
	cout<<"Input messages:"<<endl;
	cin>>outBuf;
	cout<<"Sending message..."<<endl;
	ret=Send();
	if(ret == -1){
		Err();
		return false;	
	}		
	cout<<"Done."<<endl;
	
	ret=Receive();
	if(ret == -1){
		Err();
		return false;	
	}
	cout<<"From Server: "<<inBuf<<endl;
	
	return true;
}
